<template>
    <template v-if="completed">
        <router-view />
    </template>
</template>
<script setup>
import useAppStore from '@/store/app'
import { computed } from "vue"
import ls from '@/lib/ls'
import { closeWebSocket, initWebSocket, sendWebSocket } from '@/utils/websocket'
import useConfigStore from '@/store/config'
const configStore = useConfigStore()

const router = useRouter()
const appStore = useAppStore()
const completed = computed(() => appStore.completed)

// 监听是否登录
watch(configStore.isLogin,(newValue,oldValue)=>{
  console.log(newValue);
    if(newValue.state == 1){
      ls.set('IS_Login',1)
      connectMsg()
    }else{
      closeWs()
      ls.remove('IS_Login',1)
    }
})
   // 在 body 上添加点击事件监听器
const handleClick = () => {
    resetTimeout();  // 每次点击时更新 lastTime
};

onMounted(()=> {
    if(ls.get('IS_Login')){
        connectMsg()
    }

// 页面加载时启动计时器
 
  // 添加事件监听器
  document.body.addEventListener('click', handleClick);

})
// console.log(configStore.isLogin.state);
// const userInfo = ls.get("USER_INFO");
//   const wsObj = {
//     msgReceivePage:"",
//     msgType: "offline",
//     platform:"1",//0：后台 1：PC 2：H5  3：小程序
//     msgContent:{
//           userCode:userInfo.userCode
//     }
//   }
//   sendWebSocket(wsObj)

// ----------------------------------------------- 长链接 ----------------------------------------------------------
//连接设备  （具体路径和后端规定）
const connectMsg = () => {
  if (!configStore.isConnected) {
    const toIp = import.meta.env.VITE_WS
    configStore.connect()
    initWebSocket(toIp)
  }
}

// 设备断开
const closeWs = () => {
  if (configStore.isConnected) {
    closeWebSocket()
    configStore.disconnect()
  }
}

// ----------------------------------------------------- 15分钟未操作  退出登录 --------------------------------------------------------
const lastTime = ref(new Date().getTime()); // 初始化为当前时间
const timeout = ref(1000 * 60 * 120); // 120分钟过期时间
// const timeout = ref(5000 ); // 15分钟过期时间
// 判断是否超时
const isTimeout = () => {
  let currentTime = new Date().getTime();
  if (currentTime - lastTime.value > timeout.value) {
    if(configStore.isLogin.state == 1){ // 如果是登录状态 退出登录
      lastTime.value = new Date().getTime();
        alert("登录状态已过期，请重新登录。");
          ls.clear();
          router.replace({
              path: "/login",
            });
          closeWs();
          configStore.isLogin.state = 0;
        }
  }
};

// 更新最后操作时间
const resetTimeout = () => {
  console.log('点击');
  
  lastTime.value = new Date().getTime();
};


  // 定时检查是否超时
  const interval = setInterval(() => {
    isTimeout();
  }, 1000);

  // 页面卸载时清理定时器和事件监听器
  onBeforeUnmount(() => {
    clearInterval(interval);
    document.body.removeEventListener('click', handleClick);
  });

</script>
<style scoped lang="scss">
</style>